package com.cl.auth.cas;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.cas.CasFilter;
import org.apache.shiro.cas.CasToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import com.cl.auth.AuthService;
import com.cl.entity.UUser;

public class GCasFilter extends CasFilter {
	
		@Autowired
		private AuthService authService;
		
		private static final String ACCESS_TOKEN = "accessToken";
		
		private static final int COOKIE_MAX_AGE = 8 * 60 * 60 * 1000;
		
		private static final String COOKIE_PATH = "/";
	
	    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
	            ServletResponse response) throws Exception {
	    	// 直接使用CAS的令牌来标识登录,不再额外产生令牌
	    	String casToken = (String)((CasToken)token).getCredentials();
	        UUser user = (UUser) subject.getPrincipal();
	    	authService.saveCasToken(user, casToken);
	    	if(response instanceof HttpServletResponse) {
	    		Cookie cookie = new Cookie(ACCESS_TOKEN, casToken);
	    		cookie.setMaxAge(COOKIE_MAX_AGE);
	    		cookie.setPath(COOKIE_PATH);
	    		((HttpServletResponse) response).addCookie(cookie);
	    	}
	    	issueSuccessRedirect(request, response);
	    	return false;
	    }

}
